use bytes::{Bytes, BytesMut};

use crate::Codec;

use super::head::RtpHead;

///rtp数据包
#[derive(Debug)]
pub(crate) struct RtpData {
	pub(crate) head: RtpHead,
	pub(crate) inner: Bytes,
	pub(crate) body: Bytes,
}

impl Codec for RtpData {
	fn write_to(&self, buf: &mut BytesMut) {
		if !self.inner.is_empty() {
			buf.extend_from_slice(&self.inner);
		} else {
			self.head.write_to(buf);
			buf.extend_from_slice(&self.body);
		}
	}
	
	fn from_bytes(buf: &mut Bytes) -> tools::ResultEx<Self>
	where
		Self: Sized,
	{
		let inner = buf.clone();
		let mut buf = buf.clone();

		Ok(Self {
			head: RtpHead::from_bytes(&mut buf)?,
			inner,
			body: buf,
		})
	}
}

impl RtpData {
	pub(crate) fn new(head: RtpHead, body: Bytes) -> Self {
		Self {
			head,
			inner: Bytes::new(),
			body,
		}
	}
}
